package com.jhws.util;

  
import com.alibaba.fastjson.JSON;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;
  
  
/** *//** 
 * @author </br> <a href="mailto:fx19800215@163.com"> robert.feng</a> 
 * 
 */  
public class jsonUtil {  
      
    /** *//** 
     * 从json数组字符串中得到一个java对象列表 ,json 包含在一个{ObjectName[]}中
     * @param jsonString 
     * @param pojoClass 
     * @return 
     */  
    public static List getBeansFromJsonObjectStr(String jsonString, String ObjectName, Class pojoClass) {
    	JSONObject jsonObject = new JSONObject(jsonString);
		JSONArray jsonArray = jsonObject.getJSONArray(ObjectName);
		List list = JSON.parseArray(jsonArray.toString(), pojoClass);
		return list;
    }

    /*
    *  从一个json 对象中获取到key为data的对象，再从data对象中获取到名为ObjectName的数组
    *  格式: {"type":"updateOwner","ret_code":1,"data":{"timeStamp":1490955789,"list":[]}}
    */
	public static List getBeansFromJsonDataObject(String jsonString, String ObjectName, Class pojoClass) {
		JSONObject jsonObject = new JSONObject(jsonString);
		JSONObject dataObject = jsonObject.getJSONObject("data");
		JSONArray jsonArray = dataObject.getJSONArray(ObjectName);
		List list = JSON.parseArray(jsonArray.toString(), pojoClass);
		return list;
	}
    
    public static String beanToJsonObject(Object obj) {
    	net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(obj);
    	return jsonObj.toString();
    }
    
    public static <T> T getKeyFromJsonObject(String jsonString, String ObjectName) {
    	JSONObject jsonObject = new JSONObject(jsonString);
    	return (T) jsonObject.get(ObjectName);
    }

    /*
    * 从Json对象中获取到data子对象，再从data子对象中获取key
    */
	public static <T> T getKeyFromJsonDataObject(String jsonString, String ObjectName) {
		JSONObject jsonObject = new JSONObject(jsonString);
		JSONObject dataObject = jsonObject.getJSONObject("data");
		return (T) dataObject.get(ObjectName);
	}

    public static List getBeansFromJsonArray(String jsonString, Class pojoClass){
		List list = JSON.parseArray(jsonString, pojoClass);
		return list;
	}
  
}
